package com.crm.interceptor;

import com.crm.domain.entity.User;
import com.crm.exception.CustomException;
import com.crm.exception.ReturnViewException;
import com.crm.result.ResultEnum;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户权限鉴定拦截器：判断某次请求，当前用户是否有权限访问
 * 通过路径url拦截来鉴定权限
 */
public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 得到session
        HttpSession session = request.getSession();

        // 得到保存在session中的对象
        User u = (User) session.getAttribute("session_user");

        // 判断用户登录信息是否存在
        if (u != null) {
            // 获取当前用户的权限列表
            List<String> perms = u.getPerms();

            // 获取当前请求路径
            String url = request.getServletPath();
            System.out.println("permission handler request ===>" + url);

            /*
                在当前登录用户的权限列表中查询与当前请求路径匹配的数据
                如果查询到表示用户有权限访问
                如果没有查询到表示用户没有权限访问
             */
            for (String perm : perms) {
                if(perm != null && url.contains(perm)){
                    return true;
                }
            }

            if (url.contains("page")) {
                throw new ReturnViewException("page/error/403");
            } else {
                throw new CustomException(ResultEnum.NOT_PERMISSION);
            }
        }

        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
